package com.runchamp;

/**
 * Created by User on 12/13/2014.
 */

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;

import static com.runchamp.R.drawable.screen_logo3;

/**
 * This {@code IntentService} does the actual handling of the GCM message.
 * {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a
 * partial wake lock for this service while the service does its work. When the
 * service is finished, it calls {@code completeWakefulIntent()} to release the
 * wake lock.
 */
public class GcmIntentService extends IntentService {
    public static final int NOTIFICATION_ID = 1;
    public static final String TAG = "GCM Demo";
    NotificationCompat.Builder builder;
    private NotificationManager mNotificationManager;

    public GcmIntentService() {
        super("GcmIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = extras.getString("messageType");//gcm.getMessageType(intent);
        Log.i("GcmIntentService", extras.toString());
        if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
            /*
             * Filter messages based on message type. Since it is likely that GCM will be
             * extended in the future with new message types, just ignore any message types you're
             * not interested in, or that you don't recognize.
             */
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                sendNotification("Send error: " + extras.toString());
            } else if ("RACE_IN_ONE_HOUR".equals(messageType)) {

                Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(this)
                                .setSmallIcon(R.drawable.screen_logo3)
                                .setSound(soundUri)
                                .setPriority(2)
                                .setAutoCancel(true)
                                .setContentTitle("Get Ready!")
                                .setContentText("You have a race starting in 60 minutes!");
                // Creates an explicit intent for an Activity in your app
                Intent resultIntent = new Intent(this, RaceInfo.class);
                Bundle raceBundle = new Bundle();
                raceBundle.putString("Key", extras.getString("Key"));
                raceBundle.putString("Tags", extras.getString("Tags"));
                raceBundle.putString("Distance", extras.getString("Distance"));
                raceBundle.putString("Time", extras.getString("Time"));
                raceBundle.putString("Manager", extras.getString("Manager"));
                raceBundle.putString("ManagerId", extras.getString("ManagerId"));
                raceBundle.putString("Participants", extras.getString("Participants"));
                raceBundle.putString("Estimated", extras.getString("Estimated"));
                resultIntent.putExtras(raceBundle);

                // The stack builder object will contain an artificial back stack for the
                // started Activity.
                // This ensures that navigating backward from the Activity leads out of
                // your application to the Home screen.
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
                // Adds the back stack for the Intent (but not the Intent itself)
                stackBuilder.addParentStack(MyRaces.class);
                // Adds the Intent that starts the Activity to the top of the stack
                stackBuilder.addNextIntent(resultIntent);
                PendingIntent resultPendingIntent =
                        stackBuilder.getPendingIntent(
                                (int) (System.currentTimeMillis() & 0xfffffff),
                                PendingIntent.FLAG_UPDATE_CURRENT
                        );
                mBuilder.setContentIntent(resultPendingIntent);
                NotificationManager mNotificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                // mId allows you to update the notification later on.
                mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

            } else if ("RACE_INVITE".equals(messageType)) {

                Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                Intent homeIntent = new Intent(this, MyRaces.class);
                NotificationCompat.Builder mBuilder =
                        new NotificationCompat.Builder(this)
                                .setSmallIcon(R.drawable.screen_logo3)
                                .setSound(soundUri)
                                .setPriority(2)
                                .setAutoCancel(true)


                                .setContentTitle("Join a race!")
                                .setContentText(extras.get("inviteNickName") + " has invited you to join a race!");
                // Creates an explicit intent for an Activity in your app
                //Intent resultIntent = new Intent(this,RaceInfo.class);

                Bundle raceBundle = new Bundle();
                raceBundle.putString("Key", extras.getString("Key"));
                raceBundle.putString("Tags", extras.getString("Tags"));
                raceBundle.putString("Distance", extras.getString("Distance"));
                raceBundle.putString("Time", extras.getString("Time"));
                raceBundle.putString("Manager", extras.getString("Manager"));
                raceBundle.putString("ManagerId", extras.getString("ManagerId"));
                raceBundle.putString("Participants", extras.getString("Participants"));
                raceBundle.putString("Estimated", extras.getString("Estimated"));
                raceBundle.putString("fromInvite", "True");
                homeIntent.putExtras(raceBundle);

                // The stack builder object will contain an artificial back stack for the
                // started Activity.
                // This ensures that navigating backward from the Activity leads out of
                // your application to the Home screen.
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
                // Adds the back stack for the Intent (but not the Intent itself)
                //stackBuilder.addParentStack(MyRaces.class);
                // Adds the Intent that starts the Activity to the top of the stack
                stackBuilder.addNextIntent(homeIntent);
                PendingIntent resultPendingIntent =
                        stackBuilder.getPendingIntent(
                                (int) (System.currentTimeMillis() & 0xfffffff),
                                PendingIntent.FLAG_UPDATE_CURRENT
                        );
                mBuilder.setContentIntent(resultPendingIntent);
                NotificationManager mNotificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                // mId allows you to update the notification later on.
                mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
            } else if ("RACER_READY".equals(messageType)) {
                Intent racerReadyIntent = new Intent();
                racerReadyIntent.setAction("com.runchamp.RACER_READY");
                sendBroadcast(racerReadyIntent);
            } else if ("RACER_FINISHED".equals(messageType)) {
                Intent racerFinishedIntent = new Intent();
                racerFinishedIntent.setAction("com.runchamp.RACER_FINISHED");
                sendBroadcast(racerFinishedIntent);

            } else if ("RACE_STARTING".equals(messageType)) {
                Intent raceStartIntent = new Intent(this, LiveRace.class);
                Log.i("start race intent", extras.toString());
                Bundle raceBundle = new Bundle();
                raceBundle.putString("Key", extras.get("Key").toString());
                raceBundle.putString("Estimated", extras.get("Estimated").toString());

                Log.i("start race intent 2", extras.get("Key").toString());
                // raceBundle.putString("Tags",extras.get("Tags").toString());
                raceBundle.putString("Distance", extras.get("Distance").toString());
                String numOfParticipants = extras.get("numofparticipants").toString();
                if (numOfParticipants != null)
                    raceBundle.putString("numofparticipants", numOfParticipants);

                // raceBundle.putString("Time",extras.get("Time").toString());
                //raceBundle.putString("Manager",extras.get("Manager").toString());
//                raceBundle.putString("Participants",extras.get("Participants").toString());
                raceStartIntent.putExtras(raceBundle);
                intent.putExtras(raceBundle);
                SharedPreferences sharedPreferences = getSharedPreferences("MyPrefsFile", MODE_PRIVATE);
                String userID = sharedPreferences.getString("userID", null);

                raceStartIntent.putExtra("user", userID);
                raceStartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                startActivity(raceStartIntent);

                //sendNotification("Race: " + extras.toString()+" is starting!");
                // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                // This loop represents the service doing some work.
                for (int i = 0; i < 5; i++) {
                    Log.i(TAG, "Working... " + (i + 1)
                            + "/5 @ " + SystemClock.elapsedRealtime());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                }
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                // Post notification of received message.
                sendNotification("Received: " + extras.toString());
                Log.i(TAG, "Received: " + extras.toString());
            }
        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    // Put the message into a notification and post it.
    // This is just one simple example of what you might choose to do with
    // a GCM message.
    private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, LiveRace.class), 0);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(screen_logo3)
                        .setContentTitle("GCM Notification")
                        .setStyle(new NotificationCompat.BigTextStyle()
                                .bigText(msg))
                        .setContentText(msg);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
}
